import { computed, ref, reactive, type Ref } from "vue";
import { ElMessageBox } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";
import editForm from "../form/index.vue";
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";

// 定义表格列类型
interface TableColumnList {
  label: string;
  prop: string;
  width?: number | string;
  minWidth?: number | string;
  fixed?: string;
  type?: string;
  slot?: string;
  cellRenderer?: Function;
  [key: string]: any;
}

export function useLoginBind(tableRef: Ref) {
  //表单数据
  const form = reactive({
    UserFilter: "",
    BindType: "",
    Status: "",
    SearchTerm: "",
    OrderBy: ""
  });

  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  //分页数据
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 表格列定义
  const columns: TableColumnList[] = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      prop: "selection",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "Id",
      width: 90
    },
    {
      label: "用户ID",
      prop: "UserId",
      width: 90
    },
    {
      label: "用户名称",
      prop: "UserName",
      minWidth: 130
    },
    {
      label: "绑定类型",
      prop: "BindType",
      minWidth: 120,
      cellRenderer: (scope: any) => {
        const typeMap = {
          account: (
            <span class="inline-block px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-xs">
              账号密码
            </span>
          ),
          sim: (
            <span class="inline-block px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
              SIM卡关联
            </span>
          )
        };
        return typeMap[scope.row.BindType] || scope.row.BindType;
      }
    },
    {
      label: "主关联码",
      prop: "MainBindCode",
      minWidth: 150
    },
    {
      label: "从关联码",
      prop: "SlaveBindCode",
      minWidth: 150
    },
    {
      label: "三关联码",
      prop: "ThreeBindCode",
      minWidth: 150
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 100,
      cellRenderer: (scope: any) => {
        return scope.row.Status === 1 ? (
          <span class="inline-block px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">
            正常
          </span>
        ) : (
          <span class="inline-block px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">
            异常
          </span>
        );
      }
    },
    {
      label: "租户ID",
      prop: "TenantId",
      width: 90
    },
    {
      label: "租户名称",
      prop: "TenantName",
      minWidth: 130
    },
    {
      label: "经销商ID",
      prop: "DealerId",
      width: 110
    },
    {
      label: "经销商名称",
      prop: "DealerName",
      minWidth: 130
    },
    {
      label: "创建时间",
      prop: "CreateTime",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      prop: "operation",
      width: 180,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 搜索功能
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      UserFilter: form.UserFilter,
      BindType: form.BindType,
      Status: form.Status,
      SearchTerm: form.SearchTerm,
      OrderBy: form.OrderBy
    };

    http
      .post(changeHttpLink("/api/loginBind/list"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 重置表单
  function resetForm(formRef: any) {
    if (!formRef) return;
    formRef.resetFields();
    Object.keys(form).forEach(key => {
      form[key] = "";
    });
    onSearch();
  }

  // 打开弹窗
  function openDialog(type = "新增", row = {}) {
    addDialog({
      title: `${type}用户登录绑定`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "600px",
      draggable: true,
      contentRenderer: () => editForm,
      beforeSure: done => {
        // 表单验证通过后关闭弹窗并刷新数据
        done();
        onSearch();
      }
    });
  }

  // 删除单条数据
  function handleDelete(row: any) {
    return new Promise(resolve => {
      ElMessageBox.confirm(
        `是否确认删除ID为${row.Id}的这条绑定数据?`,
        "系统提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          draggable: true
        }
      )
        .then(() => {
          loading.value = true;
          http
            .post(changeHttpLink("/api/loginBind/delete"), {
              data: { ids: [row.Id] }
            })
            .then((res: any) => {
              loading.value = false;
              if (res.Success) {
                message(`删除成功`, { type: "success" });
                onSearch();
                resolve(true);
              } else {
                message(res.Message, { type: "error" });
                resolve(false);
              }
            })
            .catch(err => {
              loading.value = false;
              message(err.message, { type: "error" });
              resolve(false);
            });
        })
        .catch(() => {
          resolve(false);
        });
    });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `确认要删除选中的${curSelected.length}条数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/loginBind/delete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已成功删除${curSelected.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页相关方法
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  //多选框变化
  function handleSelectionChange(val: any[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }
  //多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 初始化加载数据
  onSearch();

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate: () => {},
    handleDelete,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    onSelectionCancel
  };
}
